﻿#include <QGridLayout>
#include <QLineEdit>
#include <QLabel>
#include <QVBoxLayout>
#include <QMessageBox>
#include <QTimer>
#include "JZPropertyEditor.h"

JZPropertyEditor::JZPropertyEditor(QWidget *widget)
    :QWidget(widget)
{
    m_browser = new JZPropertyBrowser();
    
    QVBoxLayout *l = new QVBoxLayout();
    l->setContentsMargins(0,0,0,0);
    l->addWidget(m_browser);
    setLayout(l);
    
    m_editing = false;
    connect(m_browser,&JZPropertyBrowser::valueChanged,this,&JZPropertyEditor::onValueChanged);
}

JZPropertyEditor::~JZPropertyEditor()
{
}

void JZPropertyEditor::clear()
{             
    m_browser->clear();
    m_propMap.clear();
}

void JZPropertyEditor::dataToUi()
{
    m_editing = true;
    auto it = m_propMap.begin();
    while (it != m_propMap.end())
    {
        JZProperty *prop = it.key();
        PropVistior *vistor = it->data();
        prop->setValue(vistor->value());

        it++;
    }
    m_editing = false;
}

void JZPropertyEditor::uiToData()
{
    auto it = m_propMap.begin();
    while (it != m_propMap.end())
    {
        JZProperty *prop = it.key();
        PropVistior *vistor = it->data();
        vistor->setValue(prop->value());

        it++;
    }
}

void JZPropertyEditor::onValueChanged(JZProperty *p, const QVariant &value)
{            
    if (!m_propMap.contains(p))
        return;

    m_propMap[p]->setValue(value);
}

JZPropertyBrowser *JZPropertyEditor::browser()
{
    return m_browser;
}

JZProperty *JZPropertyEditor::addGroup(QString name)
{
    JZPropertyGroup *p = new JZPropertyGroup(name);
    m_browser->addProperty(p);
    return p;
}

JZProperty *JZPropertyEditor::addPropFile(QString name, QString *ptr, QString filter, JZProperty *parent)
{
    PropVistiorPtr vistor = PropVistiorPtr(new PropVistiorImpl<QString>(ptr));
    JZProperty *prop = new JZPropertyFilePath(name, filter);
    addProp(prop, vistor, parent);
    return prop;
}

JZProperty *JZPropertyEditor::addPropDir(QString name, QString *ptr, JZProperty *parent)
{
    PropVistiorPtr vistor = PropVistiorPtr(new PropVistiorImpl<QString>(ptr));
    JZProperty *prop = new JZPropertyDir(name);
    addProp(prop, vistor, parent);
    return prop;
}

void JZPropertyEditor::addProp(JZProperty *prop, PropVistiorPtr vistor, JZProperty *parent)
{
    if (parent)
        parent->addSubProperty(prop);
    else
        m_browser->addProperty(prop);

    m_propMap[prop] = vistor;
}